from datetime import datetime
from typing import Optional, List
from sqlmodel import SQLModel, Field, Relationship
from sqlalchemy import VARCHAR, Integer, Text
from .base_model import BaseEntity


class User(BaseEntity, table=True):
    __tablename__ = "user"
    __table_args__ = {"comment": "用户表"}
    uname: Optional[str]
    pwd: Optional[str]
    role: int = Field(default=1, description="角色：0-管理员 1-普通用户")
    openid: Optional[str] = Field(
        default=None,
        description="用户的微信OpenID",
    )
    nickname: Optional[str] = Field(description="昵称")
    phone: Optional[str] = Field(
        default=None,
        description="用户的手机号",
    )
    headimgurl: Optional[str] = Field(description="头像")
    is_active: int = Field(default=0, description="用户状态：0-禁用 1-启用（default）")

    message_of_user: List["Message"] = Relationship(
        back_populates="user", cascade_delete=True
    )
    log_of_user: List["Log"] = Relationship(back_populates="user", cascade_delete=True)


class Message(BaseEntity, table=True):
    __tablename__ = "user_message"
    __table_args__ = {"comment": "用户发的消息"}
    user_id: Optional[int] = Field(foreign_key="user.id")
    user: "User" = Relationship(back_populates="message_of_user")
    msg_title: Optional[str] = Field(description="标题")
    msg_content: Optional[str] = Field(description="内容")


class Log(BaseEntity, table=True):
    __tablename__ = "user_log"
    __table_args__ = {"comment": "用户日志"}
    uname: Optional[str]
    # 如果在尝试登录时，是没有uid的
    user_id: Optional[int] = Field(default=None, foreign_key="user.id")
    user: "User" = Relationship(back_populates="log_of_user")
    log_type: int = Field(
        default=0, description="日志类型：0-登录日志（default） 1-操作日志。。。"
    )
    log_level: int = Field(
        default=0,
        description="日志级别：0-info（default） 1-debug 2-warning 3-error。。。",
    )
    log_content: Optional[str] = Field(description="日志内容")
